/* eslint-disable react-hooks/exhaustive-deps */
import { useSearchParams, URLSearchParamsInit } from "react-router-dom";
import { useCallback, useMemo } from "react";
import { pureObject, isFalsy } from "utils";

export const useUrlQueryParam = <K extends string>(keys: K[]) => {
  const [searchParams, setSearchParams] = useSearchParams();

  const params = useMemo(() => {
    return keys.reduce((prev, cur) => {
      return { ...prev, [cur]: searchParams.get(cur) || "" };
    }, {} as Record<K, string>);
  }, [searchParams]);

  const updatePaeams = useCallback(
    (param: Partial<Record<K, unknown>>) => {
      const o = pureObject(
        { ...Object.fromEntries(searchParams), ...param },
        isFalsy
      ) as URLSearchParamsInit;
      return setSearchParams(o);
    },
    [searchParams]
  );

  return [params, updatePaeams] as const;
};
